package server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ChatServer {
	private List<Socket> chatroom=new ArrayList<Socket>();
	public void start(int port) throws Exception {
		ServerSocket server = new ServerSocket(port);
		
		while (true) {
			final Socket socket = server.accept();
			//socket放入集合，表示聊天室
			chatroom.add(socket);
			//子线程维护Socket，表示与一个客户端的连接
			new Thread(){
				public void run() {
					try {
						ObjectInputStream in = new ObjectInputStream(
								socket.getInputStream());
//						ObjectOutputStream out = new ObjectOutputStream(
//								socket.getOutputStream());
						Object o = in.readObject();
						System.out.println(o);
						for(Socket sk:chatroom){
							new ObjectOutputStream(sk.getOutputStream()).writeObject(o);
						}
						
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				};
			}.start();
			
//			out.close();
//			in.close();
//			socket.close();
		}

	}

	public static void main(String[] args) {
		int port = 8000;
		ChatServer server = new ChatServer();
		try {
			server.start(port);
		} catch (Exception e) {
			System.out.println("服务器启动错误！！！");
		}
	}
}
